import zipfile
import os
from .logger import LOG


def zip_folder(folder_path, output_dir):
    if not os.path.exists(folder_path):
        LOG.error(f'Folder "{folder_path}" does not exist.')
        return None

    folder_name = os.path.basename(folder_path)
    output_path = os.path.join(output_dir, f'{folder_name}.zip')

    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, _, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                zipf.write(file_path, os.path.relpath(file_path, folder_path))

    LOG.info(f'压缩完成 {output_path}')
    return output_path


if __name__ == '__main__':
    folder_path = '../../test/book1'
    output_dir = '../output_files'
    zip_file_path = zip_folder(folder_path, output_dir)

    if zip_file_path:
        print(f"压缩后的文件路径为: {zip_file_path}")